package com.zealcomm.ivcscustomer.webview

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.webkit.WebSettings
import android.webkit.WebView
import android.widget.LinearLayout
import com.just.agentweb.AgentWeb
import com.just.agentweb.AgentWebConfig
import com.just.agentweb.DefaultWebClient
import com.zco.util.LogUtil
import com.zealcomm.commonui.base.BaseCallback
import com.zealcomm.commonui.base.BaseFragment
import com.zealcomm.ivcscustomer.R
import com.zealcomm.ivcscustomer.databinding.FragmentWebviewBinding
import com.zealcomm.utils.WebViewHelper
import com.zealcomm.utils.bindView
import android.os.Build
import android.text.TextUtils
import android.webkit.ValueCallback
import androidx.annotation.RequiresApi
import com.just.agentweb.WebChromeClient
import com.zco.util.FileUtil
import com.zco.util.LogUtil.d
import java.io.File


class WebViewFragment : BaseFragment() {

    private val REQUEST_CODE_FILE_CHOOSER = 2001
    private val binding: FragmentWebviewBinding by bindView()
    private var mAgentWeb: AgentWeb? = null
    private var javascriptInterfaces: HashMap<String, MyJavascriptInterface>? = null
    private var webViewHelper: WebViewHelper? = null
    private var mUploadMessage: ValueCallback<*>? = null

    override val layoutId: Int
        get() = R.layout.fragment_webview

    @SuppressLint("JavascriptInterface")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        var url = arguments!!.getString("url")
//        url = "https://www.baidu.com"
        mAgentWeb = AgentWeb.with(this)
            .setAgentWebParent(
                binding.webLl!!,
                -1,
                LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT
                )
            )
            .useDefaultIndicator(-1, 3)
            .setWebChromeClient(object : WebChromeClient() {
                // 处理文件上传问题
                // For Android 3.0+
                override fun openFileChooser(uploadMsg: ValueCallback<Uri?>) {
                    mUploadMessage = uploadMsg
                    val i = Intent(Intent.ACTION_GET_CONTENT)
                    i.addCategory(Intent.CATEGORY_OPENABLE)
                    i.type = "*/*"
                    startActivityForResult(
                        Intent.createChooser(i, "File Chooser"),
                        REQUEST_CODE_FILE_CHOOSER
                    )
                }

                // For Android 3.0+
                override fun openFileChooser(uploadMsg: ValueCallback<*>, acceptType: String?) {
                    mUploadMessage = uploadMsg
                    val i = Intent(Intent.ACTION_GET_CONTENT)
                    i.addCategory(Intent.CATEGORY_OPENABLE)
                    val type = if (TextUtils.isEmpty(acceptType)) "*/*" else acceptType!!
                    i.type = type
                    startActivityForResult(
                        Intent.createChooser(i, "File Chooser"),
                        REQUEST_CODE_FILE_CHOOSER
                    )
                }

                // For Android 4.1
                override fun openFileChooser(
                    uploadMsg: ValueCallback<Uri?>,
                    acceptType: String?,
                    capture: String?
                ) {
                    mUploadMessage = uploadMsg
                    val i = Intent(Intent.ACTION_GET_CONTENT)
                    i.addCategory(Intent.CATEGORY_OPENABLE)
                    val type = if (TextUtils.isEmpty(acceptType)) "*/*" else acceptType!!
                    i.type = type
                    startActivityForResult(
                        Intent.createChooser(i, "File Chooser"),
                        REQUEST_CODE_FILE_CHOOSER
                    )
                }


                //Android 5.0+
                @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                override fun onShowFileChooser(
                    webView: WebView?,
                    filePathCallback: ValueCallback<Array<Uri?>?>,
                    fileChooserParams: FileChooserParams?
                ): Boolean {
                    d("UPFILE", "file chooser params：" + fileChooserParams.toString())
                    mUploadMessage = filePathCallback
                    val i = Intent(Intent.ACTION_GET_CONTENT)
                    i.addCategory(Intent.CATEGORY_OPENABLE)
                    if (fileChooserParams != null && fileChooserParams.acceptTypes != null && fileChooserParams.acceptTypes.size > 0) {
                        i.type = fileChooserParams.acceptTypes[0]
                    } else {
                        i.type = "*/*"
                    }
                    startActivityForResult(
                        Intent.createChooser(i, "File Chooser"),
                        REQUEST_CODE_FILE_CHOOSER
                    )
                    return true
                }
            })
            .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
            .setMainFrameErrorView(R.layout.agentweb_error_page, -1)
            .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.DISALLOW)
            .interceptUnkownUrl()
            .createAgentWeb()
            .ready()
            .go(url)
        AgentWebConfig.debug()
        mAgentWeb!!.webCreator.webView.overScrollMode = WebView.OVER_SCROLL_NEVER
        mAgentWeb!!.webCreator.webView.settings.javaScriptEnabled = true
        //优先使用网络
        mAgentWeb!!.webCreator.webView.settings.cacheMode = WebSettings.LOAD_DEFAULT
        //将图片调整到适合webview的大小
        mAgentWeb!!.webCreator.webView.settings.useWideViewPort = true
        //支持内容重新布局
        mAgentWeb!!.webCreator.webView.settings.layoutAlgorithm =
            WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        //支持自动加载图片
        mAgentWeb!!.webCreator.webView.settings.loadsImagesAutomatically = true
        //当webview调用requestFocus时为webview设置节点
        mAgentWeb!!.webCreator.webView.settings.setNeedInitialFocus(true)
        //自适应屏幕
        mAgentWeb!!.webCreator.webView.settings.useWideViewPort = true
        mAgentWeb!!.webCreator.webView.settings.loadWithOverviewMode = true
        //开启DOM storage API功能（HTML5 提供的一种标准的接口，主要将键值对存储在本地，在页面加载完毕后可以通过 javascript 来操作这些数据。）
        mAgentWeb!!.webCreator.webView.settings.domStorageEnabled = true
        //支持缩放
        mAgentWeb!!.webCreator.webView.settings.builtInZoomControls = true
        mAgentWeb!!.webCreator.webView.settings.setSupportZoom(true)

        //允许webview对文件的操作
        mAgentWeb!!.webCreator.webView.settings.allowFileAccess = true
        mAgentWeb!!.webCreator.webView.settings.allowFileAccessFromFileURLs = true
        mAgentWeb!!.webCreator.webView.settings.allowUniversalAccessFromFileURLs = true
        mAgentWeb!!.webCreator.webView.setOnKeyListener { v: View?, keyCode: Int, event: KeyEvent ->
            if (event.action == KeyEvent.ACTION_DOWN) {
                if (keyCode == KeyEvent.KEYCODE_BACK && mAgentWeb!!.webCreator.webView.canGoBack()) { // 表示按返回键时的操作
                    mAgentWeb!!.webCreator.webView.goBack()
                    return@setOnKeyListener true
                } else if (keyCode == KeyEvent.KEYCODE_BACK) {
                    activity!!.moveTaskToBack(true)
                }
            }
            false
        }
        javascriptInterfaces?.let {
            it.keys?.forEach { key ->
                mAgentWeb!!.webCreator.webView.addJavascriptInterface(it[key]!!, key)
            }
        }
        setListeners()
    }

    override fun initView(view: View?, savedInstanceState: Bundle?) {
    }

    private fun setListeners() {
        binding.actionBar.back.setOnClickListener {
            removeFragment()
        }
    }

    override fun onResume() {
        mAgentWeb?.webLifeCycle?.onResume()
        super.onResume()
    }

    override fun onPause() {
        mAgentWeb?.webLifeCycle?.onPause()
        super.onPause()
    }

    override fun onDestroyView() {
        mAgentWeb?.webLifeCycle?.onDestroy()
        super.onDestroyView()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                REQUEST_CODE_FILE_CHOOSER -> {
                    data?.let {
                        uploadFileToWebView(it)
                    }
                }
            }
        }
    }

    private fun uploadFileToWebView(data: Intent?) {
        if (null == mUploadMessage) return
        val result = data?.data
        if (result == null) {
            mUploadMessage!!.onReceiveValue(null)
            mUploadMessage = null
            return
        }
        val path = FileUtil.getPath(activity, result)
        if (TextUtils.isEmpty(path)) {
            mUploadMessage!!.onReceiveValue(null)
            mUploadMessage = null
            return
        }
        val uri = Uri.fromFile(File(path))
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            (mUploadMessage as ValueCallback<Any>)!!.onReceiveValue(arrayOf(uri))
        } else {
            (mUploadMessage as ValueCallback<Any>)!!.onReceiveValue(uri)
        }
        mUploadMessage = null
    }

    companion object {
        fun getInstance(url: String?, callback: BaseCallback?): WebViewFragment {
            val fragment = WebViewFragment()
            val args = Bundle()
            args.putString("url", url)
            fragment.arguments = args
            fragment.setBaseCallback(callback)
            return fragment
        }

        fun getInstance(
            url: String?,
            javascriptInterfaces: HashMap<String, MyJavascriptInterface>,
            callback: BaseCallback?
        ): WebViewFragment {
            val fragment = WebViewFragment()
            LogUtil.d("要打开的url：$url")
            fragment.javascriptInterfaces = javascriptInterfaces
            val args = Bundle()
            args.putString("url", url)
            fragment.arguments = args
            fragment.setBaseCallback(callback)
            return fragment
        }
    }
}